const router = require('koa-router')();
const passport = require('koa-passport');
const events=require('events');
const isLoggedout=require('../middlewares/isLoggedout');

router.get('/',isLoggedout(), async (ctx, next) => {
    await ctx.render('passport', {
        title: [ctx.locals.name, 'Passport'].join('-'),
        loginUser: ctx.session.loginUser,
        success: ctx.flash.success,
        error: ctx.flash.error
    });
});

router.post('/',isLoggedout(),async (ctx,next)=>{
    let {username,password}=ctx.request.body,ee=new events();
    ee.on('fail',msg=>{
        ctx.flash={error:msg};
        ctx.redirect('back');
    });
    if(!username || !password)return ee.emit('fail','用户名或密码未输入');
    await next();
},async (ctx,next)=>{
    return passport.authenticate('local', (err, user, msg)=>{
        if (err) return next(err);
        if (!user) {
            ctx.flash={error:msg};
            return ctx.redirect('/login');
        }
        ctx.logIn(user, function(err) {
            if (err) return next(err);
            ctx.flash={success:'登录成功'};
            ctx.redirect('/');
        });
    })(ctx,next);
});

module.exports = router;